<template>
    <div v-loading="pageLoading">
        <!-- 返回 -->
        <el-card shadow="never" class="!border-none">
            <el-page-header
                :content="'畅阅模式' + (formData.id ? '编辑' : '新增')"
                @back="emits('listen', 'lists')"
            />
        </el-card>

        <!-- 表单 -->
        <el-form ref="formRef" :rules="rules" :model="formData" label-width="90px">
            <el-card shadow="never" class="!border-none mt-4">
                <div class="text-xl font-medium mb-6">基础配置</div>
                <el-form-item label="模式图标" prop="icon">
                    <div class="w-[400px]">
                        <material-picker
                            v-model="formData.icon"
                            :limit="1"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="模式名称" prop="name">
                    <div class="w-[400px]">
                        <el-input
                            v-model="formData.name"
                            placeholder="请输入模式名称"
                            maxlength="100"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="模式描述" prop="intro">
                    <div class="w-[400px]">
                        <el-input
                            v-model="formData.intro"
                            placeholder="请输入模式描述"
                            maxlength="100"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="排序" prop="sort" required>
                    <el-input-number v-model="formData.sort" :min="0" :max="999999" />
                </el-form-item>
                <el-form-item label="状态" prop="is_disable">
                    <div class="w-[400px]">
                        <el-radio-group v-model="formData.is_disable">
                            <el-radio :value="0">正常</el-radio>
                            <el-radio :value="1">停用</el-radio>
                        </el-radio-group>
                    </div>
                </el-form-item>
            </el-card>

            <!-- 对话 -->
            <el-card shadow="never" class="!border-none mt-4">
                <div class="text-xl font-medium mb-6">【对话】提示词</div>
                <el-form-item label="AI模型" prop="models_dialogue">
                    <div class="w-[400px]">
                        <models-select
                            v-model="formData.models_dialogue"
                            @change="changeDialogue"
                        />
                    </div>
                </el-form-item>
                <template v-for="(conf, index) in formData.config_dialogue" :key="index">
                    <template v-if="conf.type === 'slider'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <div class="w-[400px]">
                                <el-slider
                                    v-model="formData.config_dialogue[index].default"
                                    :min="conf.range[0]"
                                    :max="conf.range[1]"
                                    :step="conf.step"
                                    show-input
                                />
                            </div>
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                    <template v-if="conf.type === 'switch'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <el-switch v-model="formData.config_dialogue[index].default" />
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                </template>
                <el-form-item label="提示词" prop="prompt_dialogue">
                    <div class="w-[600px]">
                        <el-input
                            type="textarea"
                            :rows="8"
                            v-model.trim="formData.prompt_dialogue"
                            show-word-limit
                        />
                    </div>
                </el-form-item>
            </el-card>

            <!-- 总结 -->
            <el-card shadow="never" class="!border-none mt-4">
                <div class="text-xl font-medium mb-6">【总结】提示词</div>
                <el-form-item label="AI模型" prop="models_abstract">
                    <div class="w-[400px]">
                        <models-select
                            v-model="formData.models_abstract"
                            @change="changeAbstract"
                        />
                    </div>
                </el-form-item>
                <template v-for="(conf, index) in formData.config_abstract" :key="index">
                    <template v-if="conf.type === 'slider'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <div class="w-[400px]">
                                <el-slider
                                    v-model="formData.config_abstract[index].default"
                                    :min="conf.range[0]"
                                    :max="conf.range[1]"
                                    :step="conf.step"
                                    show-input
                                />
                            </div>
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                    <template v-if="conf.type === 'switch'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <el-switch v-model="formData.config_abstract[index].default" />
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                </template>
                <el-form-item label="提示词" prop="prompt_abstract">
                    <div class="w-[600px]">
                        <el-input
                            type="textarea"
                            :rows="8"
                            v-model.trim="formData.prompt_abstract"
                            show-word-limit
                        />
                    </div>
                </el-form-item>
            </el-card>

            <!-- 翻译 -->
            <el-card shadow="never" class="!border-none mt-4">
                <div class="text-xl font-medium mb-6">【翻译】提示词</div>
                <el-form-item label="AI模型" prop="models_translate">
                    <div class="w-[400px]">
                        <models-select
                            v-model="formData.models_translate"
                            @change="changeTranslate"
                        />
                    </div>
                </el-form-item>
                <template v-for="(conf, index) in formData.config_translate" :key="index">
                    <template v-if="conf.type === 'slider'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <div class="w-[400px]">
                                <el-slider
                                    v-model="formData.config_translate[index].default"
                                    :min="conf.range[0]"
                                    :max="conf.range[1]"
                                    :step="conf.step"
                                    show-input
                                />
                            </div>
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                    <template v-if="conf.type === 'switch'">
                        <el-form-item :label="conf.name" :prop="conf.key">
                            <el-switch v-model="formData.config_translate[index].default" />
                            <template v-slot:label>
                                {{ conf.name }}
                                <el-tooltip placement="top" :content='conf.tips'>
                                    <icon name="el-icon-question-filled" class="ml-1" />
                                </el-tooltip>
                            </template>
                        </el-form-item>
                    </template>
                </template>
                <el-form-item label="提示词" prop="prompt_translate">
                    <div class="w-[600px]">
                        <el-input
                            type="textarea"
                            :rows="8"
                            v-model.trim="formData.prompt_translate"
                            show-word-limit
                        />
                    </div>
                </el-form-item>
            </el-card>

            <!-- 按钮 -->
            <el-card shadow="never" class="!border-none mt-4 text-center">
                <el-button @click="emits('listen', '', 'lists', 0)">取消</el-button>
                <el-button
                    v-perms="['setting:ai:models:add', 'setting:ai:models:edit']"
                    :loading="loading"
                    type="primary"
                    @click="handleSubmit"
                >保存</el-button>
            </el-card>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import feedback from '@/utils/feedback'
import docsPromptApi from '@/api/apply/docs/prompt'

const emits = defineEmits(['listen'])
const props = defineProps({
    id: {
        type: Number,
        default: 0
    }
})

// 页面加载
const pageLoading = ref<boolean>(false)

// 表单数据
const loading = ref<boolean>(false)
const formRef = ref()
const formData = ref<any>({
    id: '',               // ID
    code: '',             // 编号
    icon: '',             // 图标
    name: '',             // 名称
    intro: '',            // 简介
    is_disable: 0,        // 是否禁用:[0=否, 1=是]
    // 提示词
    prompt_dialogue: '',  // 对话提示词
    prompt_abstract: '',  // 总结提示词
    prompt_translate: '', // 翻译提示词
    // 模型名
    models_dialogue: '',  // 对话模型名称
    models_abstract: '',  // 总结模型名称
    models_translate: '', // 翻译模型名称
    // 模型参数
    config_dialogue: [],  // 对话模型参数
    config_abstract: [],  // 总结模型参数
    config_translate: []  // 翻译模型参数
})

// 表单验证
const rules = {
    'icon': [
        { required: true, message: '请上传模式图标', trigger: 'blur' }
    ],
    'name': [
        { required: true, message: '模式名称不能为空', trigger: 'blur' }
    ],
    'intro': [
        { required: true, message: '模式描述不能为空', trigger: 'blur' }
    ],
    'is_disable': [
        { required: true, message: '请正确选择状态开关', trigger: 'blur' }
    ],
    'models_dialogue': [
        { required: true, message: '请正确选择对话模型', trigger: 'blur' }
    ],
    'models_abstract': [
        { required: true, message: '请正确选择总结模型', trigger: 'blur' }
    ],
    'models_translate': [
        { required: true, message: '请正确选择翻译模型', trigger: 'blur' }
    ],
    'prompt_dialogue': [
        { required: true, message: '对话提示词不能为空', trigger: 'blur' }
    ],
    'prompt_abstract': [
        { required: true, message: '总结提示词不能为空', trigger: 'blur' }
    ],
    'prompt_translate': [
        { required: true, message: '翻译提示词不能为空', trigger: 'blur' }
    ]
}

/**
 * 对话模型变动
 */
const changeDialogue = (data: any) => {
    formData.value.models_dialogue = data.name
    formData.value.config_dialogue = data.config
}

/**
 * 总结模型变动
 */
const changeAbstract = (data: any) => {
    formData.value.models_abstract = data.name
    formData.value.config_abstract = data.config
}

/**
 * 翻译模型变动
 */
const changeTranslate = (data: any) => {
    formData.value.models_translate = data.name
    formData.value.config_translate = data.config
}

/**
 * 提交表单
 */
const handleSubmit = async (): Promise<void> => {
    // 验证模型参数
    if (formData.value.config_dialogue.length <= 0) {
        return feedback.msgError('对话模型选择异常,请重新选择!')
    }
    if (formData.value.config_abstract.length <= 0) {
        return feedback.msgError('对话模型选择异常,请重新选择!')
    }
    if (formData.value.config_translate.length <= 0) {
        return feedback.msgError('对话模型选择异常,请重新选择!')
    }

    // 处理模型参数
    let config_dialogue: any = {}
    formData.value.config_dialogue.forEach((item: any) => {
        config_dialogue[item.key] = item.default
    })

    let config_abstract: any = {}
    formData.value.config_abstract.forEach((item: any) => {
        config_abstract[item.key] = item.default
    })

    let config_translate: any = {}
    formData.value.config_translate.forEach((item: any) => {
        config_translate[item.key] = item.default
    })

    // 处理提交参数
    let params = Object.assign({}, formData.value)
    params.config_dialogue = config_dialogue
    params.config_abstract = config_abstract
    params.config_translate = config_translate

    // 发起提交请求
    await formRef.value?.validate().then(async () => {
        loading.value = true
        if (props.id) {
            await docsPromptApi.edit(params)
                .finally(() => {
                    loading.value = false
                })
        } else {
            delete params.id
            await docsPromptApi.add(params)
                .finally(() => {
                    loading.value = false
                })
        }

        feedback.msgSuccess('操作成功')
        emits('listen', 'lists')
    }).catch(() => {})
}

watch(
    () => props.id,
    async () => {
        if (props.id) {
            pageLoading.value = true
            formData.value = await docsPromptApi.detail(props.id)
            pageLoading.value = false
        }
    },
    { immediate: true }
)
</script>
